import os
import numpy as np
from PIL import Image
from openpyxl import load_workbook


def export_and_record_image_positions(excel_path, output_folder, SheetName):
    # 加载 Excel 文件
    workbook = load_workbook(filename=excel_path)
    # 选择要处理的工作表
    worksheet = workbook[SheetName]

    # 获取工作表中的所有图像
    images = worksheet._images
    image_positions = {}
    index = 0

    for image in images:
        # 获取图像的左上角和右下角坐标
        row = image.anchor.to.row
        column = image.anchor.to.col
        print(f"Image position: " + f"row: {row}, column: {column}")
        type = image.format
        print("图片的类型是：\t" + type)
        pic_half = SheetName + 'pic'
        pic_half_lowercase = pic_half.lower()
        index += 1
        pic_name = pic_half_lowercase + str(index) + "." + type  # 输出图片名称

        data = image.ref
        with open(os.path.join(output_folder, pic_name), 'wb') as img_file:
            img_pil = Image.open(image.ref)
            width, height = img_pil.size

            # 如果图片尺寸大于1980x1080，则进行缩放
            if width > 1980 or height > 1080:
                img_pil.thumbnail((1980, 800))
            # 转换为RGB模式（如果原图不是RGB）
            img_pil = img_pil.convert("RGB")
            img_pil.save(os.path.join(output_folder, pic_name))
            # 记录图片位置信息（这里假设仍需要记录）
        image_positions[row-1] = pic_name

    return image_positions


if __name__ == '__main__':
    excel_path = r"C:\Users\·jiazi\PycharmProjects\pythonProject1\PBLEducationProject\Examples\wanDan.xlsx"
    output_folder = r"C:\Users\·jiazi\PycharmProjects\pythonProject1\PBLEducationProject\output"
    ans = export_and_record_image_positions(excel_path, output_folder, 'Sheet2')
    print(ans)
